package com.rotai.hw.myapplication;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import android_serialport_api.SerialPort;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

public class MainActivity extends Activity implements View.OnClickListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private Button btn_start, btn_stop;

    private LineChartView lineChartView;
    private LineChartData lineChartData;
    private List<Line> lineList;


    private Axis axisX;
    private Axis axisY;

    private List<PointValue> pointValueList;
    private List<PointValue> points;

    private Handler mHandler;

    private boolean isFinish = false;
    private int position = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();

        initAxisView();
        showMovingLineChart();
        start();
    }

    private void initViews() {
        btn_start = findViewById(R.id.btn_start);
        btn_stop = findViewById(R.id.btn_stop);
        btn_stop.setOnClickListener(this);
        btn_start.setOnClickListener(this);
    }

    /**
     * 数据点动态刷新
     */
    private void showMovingLineChart() {

        mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (!isFinish) {
                    pointValueList.add(points.get(position));
                    Line line = new Line(pointValueList);
                    line.setColor(Color.parseColor("#FFCD41"));
                    line.setShape(ValueShape.CIRCLE);
                    line.setCubic(true);
                    line.setHasLabels(true);
                    //                    line.setHasLabelsOnlyForSelected(true);
                    line.setHasLines(true);
                    line.setHasPoints(true);

                    lineList.add(line);
                    lineChartData = new LineChartData(lineList);
                    lineChartData.setAxisYLeft(axisY);
                    lineChartData.setAxisXBottom(axisX);
                    lineChartView.setLineChartData(lineChartData);

                    float xAxisValue = points.get(position).getX();

                    Viewport port;
                    if (xAxisValue > 10) {
                        port = initViewPort(xAxisValue - 10, xAxisValue);
                    } else {
                        port = initViewPort(0, 10);
                    }
                    lineChartView.setMaximumViewport(port);
                    lineChartView.setCurrentViewport(port);

                    position++;

                    if (position > points.size() - 1) {
                        isFinish = true;
                    }
                }
            }
        };


    }

    /**
     * 初始化显示坐标轴
     */
    private void initAxisView() {

        lineChartView = (LineChartView) findViewById(R.id.line_chart);
        pointValueList = new ArrayList<PointValue>();
        lineList = new ArrayList<Line>();

        /**
         * 初始化Y轴
         */
        axisY = new Axis();
        axisY.setName("数值 （单位：次）");
        axisY.setHasLines(true);
        axisY.setTextSize(10);
        //        axisY.setTextColor(Color.parseColor("#AFEEEE"));
        lineChartData = new LineChartData(lineList);
        lineChartData.setAxisYLeft(axisY);

        /**
         * 初始化X轴
         */
        axisX = new Axis();
        axisX.setHasTiltedLabels(false);
        //        axisX.setTextColor(Color.BLUE);
        axisX.setName("时间 （单位：s）");
        axisX.setHasLines(true);
        axisX.setTextSize(10);
        axisX.setMaxLabelChars(1);


        List<AxisValue> mAxisXValues = new ArrayList<AxisValue>();
        for (int i = 0; i < 90; i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(i + ""));
        }
        axisX.setValues(mAxisXValues);

        lineChartData.setAxisXBottom(axisX);
        lineChartView.setLineChartData(lineChartData);

        Viewport port = initViewPort(0, 10);
        lineChartView.setCurrentViewportWithAnimation(port);
        lineChartView.setInteractive(false);
        lineChartView.setScrollEnabled(true);
        lineChartView.setValueTouchEnabled(false);
        lineChartView.setFocusableInTouchMode(false);
        lineChartView.setViewportCalculationEnabled(false);
        lineChartView.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        lineChartView.startDataAnimation();

        receiveSerialDate();

    }

    private Viewport initViewPort(float left, float right) {
        Viewport port = new Viewport();
        port.top = 100;
        port.bottom = 0;
        port.left = left;
        port.right = right;
        return port;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    /**
     * 点击事件
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start:
                start();
                break;
            case R.id.btn_stop:
                stop();
                break;
        }
    }


    /**
     * =======================================测量绘图==============================================
     */

    protected SerialPort mSerialPort;
    private String prot = "ttyHSL1";
    private int baudrate = 38400;
    protected InputStream mInputStream;
    protected OutputStream mOutputStream;
    private static int i = 0;
    public static boolean flag = false;


    /**
     * 开始测量
     */
    private void start() {
        openSerialPort();
        sendCmd1();

    }

    /**
     * 结束测量
     */
    private void stop() {
        sendCmd2();
        closeSerialPort();
    }



    /**
     * 打开串口
     */
    private void openSerialPort() {
        Log.e(TAG, "打开串口");
        try {
            mSerialPort = new SerialPort(new File("/dev/" + prot), baudrate, 0);
            mInputStream = mSerialPort.getInputStream();
            mOutputStream = mSerialPort.getOutputStream();

            flag = true;

        } catch (SecurityException e) {
            e.printStackTrace();
            Log.i("test——serial", "打开失败");
        } catch (IOException e) {
            Log.i("test——serial", "打开失败");
            e.printStackTrace();
        }
        Log.i("test——serial # flag", "" + flag);
    }

    /**
     * 发送串口打开指令
     */
    private void sendCmd1() {
        Log.e(TAG, "打开开启采集指令");
        byte[] b = hexStringToBytes("0x8A");
        try {
            mOutputStream.write(b);
            receiveSerialDate();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 发送采集关闭指令
     */
    private void sendCmd2() {
        byte[] b = hexStringToBytes("0x88");
        try {
            mOutputStream.write(b);
            receiveSerialDate();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将输入的16进制string转成字节
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * 接收串口数据
     */

    private void receiveSerialDate() {

        points = new ArrayList<PointValue>();

        Log.e(TAG, "接收串口数据");

        // 接收
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (flag) {
                    int size;
                    try {
                        byte[] buffer = new byte[76];
                        if (mInputStream == null)
                            return;
                        size = mInputStream.read(buffer);
                        if (size > 0 && flag) {
                            if (buffer[0] == (byte) 0xff) {
                                byte[] rateByte = new byte[64];
                                for (int j = 0; j < 64; j++) {
                                    rateByte[j] = (byte) -buffer[j + 1];
                                }

                                for (int i = 0; i < 64; i++) {
                                    //            points.add(new PointValue(i+1,i%5*10+30));
                                    points.add(new PointValue(i + 1, rateByte[i]));
                                }

                            }
                            //                            handler.sendEmptyMessage(1);
                            mHandler.sendEmptyMessageDelayed(50,100);
                        }
//                        Thread.sleep(1000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    /**
     * 关闭串口
     */
    public void closeSerialPort() {
        Log.e(TAG, "关闭串口");
        //        Log.i("test——serial", "关闭串口");
        i = 0;
        try {
            if (mSerialPort != null) {
                mSerialPort.close();
                Log.i("test——serial", "关闭串口");
            }

            if (mInputStream != null) {
                mInputStream.close();
                Log.i("test——serial", "关闭输入流");
            }
            if (mOutputStream != null) {
                mOutputStream.close();
                Log.i("test——serial", "关闭输出流");
            }
            flag = false;
            Log.i("test——serial", "串口关闭成功");
        } catch (IOException e) {
            Log.i("test——serial", "关闭串口失败");
            e.printStackTrace();
        }
    }

}
